package top.lixunda.ecommerce.server.good.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lixunda.common.utils.ObjectValidators;
import top.lixunda.ecommerce.server.business.BaseService;
import top.lixunda.ecommerce.server.business.api.entity.BusinessConstants;
import top.lixunda.ecommerce.server.good.api.entity.db.PageInfoShowDO;
import top.lixunda.ecommerce.server.good.api.entity.dto.PageIndexCarouselChangeDTO;
import top.lixunda.ecommerce.server.good.api.entity.dto.PageIndexCarouselInsertDTO;
import top.lixunda.ecommerce.server.good.api.entity.dto.PageIndexFeaturedChangeDTO;
import top.lixunda.ecommerce.server.good.api.entity.dto.PageIndexFeaturedInsertDTO;
import top.lixunda.ecommerce.server.good.api.entity.vo.GoodConvertVO;
import top.lixunda.ecommerce.server.good.api.entity.vo.PageCarouselVO;
import top.lixunda.ecommerce.server.good.api.entity.vo.PageFeaturedVO;
import top.lixunda.ecommerce.server.good.service.IGoodDetailService;
import top.lixunda.ecommerce.server.good.service.IPageIndexService;
import top.lixunda.ecommerce.server.good.service.IPageInfoShowService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 首页数据展示获取与设置
 *
 * @author lixunda
 * @version time:2020/3/18 16:35
 */
@Slf4j
@Service
public class PageIndexServiceImpl extends BaseService implements IPageIndexService {

    private final IPageInfoShowService pageInfoShowService;

    private final IGoodDetailService goodDetailService;

    private final IGoodDetailService getGoodDetailService;

    @Autowired
    public PageIndexServiceImpl(IPageInfoShowService pageInfoShowService,
                                IGoodDetailService goodDetailService,
                                IGoodDetailService getGoodDetailService) {
        this.pageInfoShowService = pageInfoShowService;
        this.goodDetailService = goodDetailService;
        this.getGoodDetailService = getGoodDetailService;
    }

    /**
     * 获取首页走马灯数据
     *
     * @return PageCarouselVO列表
     */
    @Override
    public List<PageCarouselVO> queryCarouselVO() {
        List<PageInfoShowDO> list = pageInfoShowService.list(
                new LambdaQueryWrapper<PageInfoShowDO>()
                        .eq(PageInfoShowDO::getPage, BusinessConstants.PAGE_NAME_INDEX)
                        .eq(PageInfoShowDO::getModule, BusinessConstants.PAGE_MODULE_NAME_CAROUSEL)
                        .orderByAsc(PageInfoShowDO::getSequence)
                        .orderByDesc(PageInfoShowDO::getCreateTime));
        if (ObjectValidators.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list.stream()
                .parallel()
                .map(item -> {
                    List<String> ids = Stream.of(item.getContent1(), item.getContent2(),
                            item.getContent3())
                            .filter(ObjectValidators::isNotEmpty)
                            .collect(Collectors.toList());
                    List<GoodConvertVO> goodList = goodDetailService.listConvertByIds(ids);
                    GoodConvertVO goodConvertVO = goodDetailService.getConvertById(item.getLink());
                    return PageCarouselVO.fromPageInfoShowDO(item, goodConvertVO, goodList);
                })
                .collect(Collectors.toList());
    }

    /**
     * 添加保存一条首页的Carousel数据
     *
     * @param pageIndexCarouselInsertDTO 保存数据
     * @return 是否保存成功
     */
    @Override
    public boolean insertIndexCarousel(PageIndexCarouselInsertDTO pageIndexCarouselInsertDTO) {
        if (ObjectValidators.isEmpty(pageIndexCarouselInsertDTO)) {
            throw getAppException("参数不能为空");
        }
        // 权限校验
        currentAdminUserCacheNotNull();
        PageInfoShowDO pageInfoShowDO = pageIndexCarouselInsertDTO.toPageInfoShowDO();
        pageInfoShowDO.setPage(BusinessConstants.PAGE_NAME_INDEX)
                .setModule(BusinessConstants.PAGE_MODULE_NAME_CAROUSEL);
        return pageInfoShowService.insertPageInfo(pageInfoShowDO);
    }

    /**
     * 添加保存多条首页的Carousel数据
     *
     * @param list 保存数据列表
     * @return 是否保存成功
     */
    @Override
    public boolean insertIndexCarouselBatch(List<PageIndexCarouselInsertDTO> list) {
        if (ObjectValidators.isEmpty(list)) {
            throw getAppException("参数不能为空");
        }
        // 权限校验
        currentAdminUserCacheNotNull();
        return pageInfoShowService.insertPageInfoBatch(list.stream()
                .map(PageIndexCarouselInsertDTO::toPageInfoShowDO)
                .map(item -> item.setPage(BusinessConstants.PAGE_NAME_INDEX)
                        .setModule(BusinessConstants.PAGE_MODULE_NAME_CAROUSEL))
                .collect(Collectors.toList()));
    }

    /**
     * 修改首页轮播图数据
     *
     * @param pageIndexCarouselChangeDTO 轮播图数据修改DTO
     * @return 是否修改成功
     */
    @Override
    public boolean changeIndexCarousel(PageIndexCarouselChangeDTO pageIndexCarouselChangeDTO) {
        if (ObjectValidators.isEmpty(pageIndexCarouselChangeDTO)) {
            throw getAppException("参数不能为空");
        }
        currentAdminUserCacheNotNull();
        PageInfoShowDO pageInfoShowDO = pageIndexCarouselChangeDTO.toPageInfoShowDO();
        return pageInfoShowService.changePageInfoById(pageInfoShowDO);
    }

    /**
     * 根据id移除数据
     *
     * @param ids 轮播图数据编号列表
     * @return 是否移除成功
     */
    @Override
    public boolean removeIndexCarouselByIds(List<Integer> ids) {
        if (ObjectValidators.isEmpty(ids)) {
            throw getAppException("参数编号不能为空");
        }
        // 权限校验
        currentAdminUserCacheNotNull();
        return pageInfoShowService.remove(new LambdaUpdateWrapper<PageInfoShowDO>()
                .in(PageInfoShowDO::getId, ids)
                .eq(PageInfoShowDO::getPage, BusinessConstants.PAGE_NAME_INDEX)
                .eq(PageInfoShowDO::getModule, BusinessConstants.PAGE_MODULE_NAME_CAROUSEL));
    }

    /**
     * 获取首页Featured数据
     *
     * @return PageFeaturedVO列表
     */
    @Override
    public List<PageFeaturedVO> queryFeaturedVO() {
        List<PageInfoShowDO> list = pageInfoShowService.list(
                new LambdaQueryWrapper<PageInfoShowDO>()
                        .eq(PageInfoShowDO::getPage, BusinessConstants.PAGE_NAME_INDEX)
                        .eq(PageInfoShowDO::getModule, BusinessConstants.PAGE_MODULE_NAME_FEATURED));
        if (ObjectValidators.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list.stream()
                .parallel()
                .map(item -> {
                    GoodConvertVO goodConvertVO = goodDetailService.getConvertById(item.getLink());
                    return PageFeaturedVO.fromPageInfoShowDO(item, goodConvertVO);
                })
                .collect(Collectors.toList());
    }

    /**
     * 添加保存一条首页的Featured数据
     *
     * @param pageIndexFeaturedInsertDTO 保存数据
     * @return 保存后的数据，为空表示失败
     */
    @Override
    public PageFeaturedVO insertIndexFeatured(PageIndexFeaturedInsertDTO pageIndexFeaturedInsertDTO) {
        if (ObjectValidators.isEmpty(pageIndexFeaturedInsertDTO)) {
            throw getAppException("参数不能为空");
        }
        Integer goodId = pageIndexFeaturedInsertDTO.getLinkGoodId();
        if (ObjectValidators.isEmpty(goodId)) {
            throw getAppException("参数错误：商品编号不能为空");
        }
        // 权限校验
        currentAdminUserCacheNotNull();
        GoodConvertVO goodConvertVO = getGoodDetailService.queryById(goodId);
        if (ObjectValidators.isEmpty(goodConvertVO)) {
            throw getAppException("保存Featured数据失败：商品" + goodId + "不存在");
        }
        PageInfoShowDO pageInfoShowDO = pageIndexFeaturedInsertDTO.toPageInfoShowDO();
        boolean success = pageInfoShowService.insertPageInfo(pageInfoShowDO);
        if (!success) {
            throw getAppException("保存Featured数据失败：插入数据失败");
        }
        pageInfoShowDO = pageInfoShowService.getById(pageInfoShowDO.getId());
        if (ObjectValidators.isEmpty(pageInfoShowDO)) {
            throw getAppException("保存Featured数据失败：查询插入的数据失败");
        }
        return PageFeaturedVO.fromPageInfoShowDO(pageInfoShowDO, goodConvertVO);
    }

    /**
     * 添加保存多条首页的Featured数据
     *
     * @param list 保存数据列表
     * @return 保存后的数据，为空表示失败
     */
    @Override
    public List<PageFeaturedVO> insertIndexFeaturedBatch(List<PageIndexFeaturedInsertDTO> list) {
        if (ObjectValidators.isEmpty(list)) {
            throw getAppException("参数不能为空");
        }
        // 权限校验
        currentAdminUserCacheNotNull();
        List<PageFeaturedVO> resultList = new ArrayList<>(list.size());
        list.forEach(item -> {
            PageFeaturedVO vo = this.insertIndexFeatured(item);
            resultList.add(vo);
        });
        return resultList;
    }

    /**
     * 修改首页Featured数据
     *
     * @param pageIndexFeaturedChangeDTO Featured数据修改DTO
     * @return 修改后的数据
     */
    @Override
    public PageFeaturedVO changeIndexFeatured(PageIndexFeaturedChangeDTO pageIndexFeaturedChangeDTO) {
        if (ObjectValidators.isEmpty(pageIndexFeaturedChangeDTO)) {
            throw getAppException("参数不能为空");
        }
        Integer goodId = pageIndexFeaturedChangeDTO.getLinkGoodId();
        if (ObjectValidators.isEmpty(goodId)) {
            throw getAppException("参数错误：商品编号不能为空");
        }
        // 权限校验
        currentAdminUserCacheNotNull();
        GoodConvertVO goodConvertVO = getGoodDetailService.queryById(goodId);
        if (ObjectValidators.isEmpty(goodConvertVO)) {
            throw getAppException("更新Featured数据失败：商品" + goodId + "不存在");
        }
        PageInfoShowDO pageInfoShowDO = pageIndexFeaturedChangeDTO.toPageInfoShowDO();
        boolean success = pageInfoShowService.changePageInfoById(pageInfoShowDO);
        if (!success) {
            throw getAppException("更新Featured数据失败：插入数据失败");
        }
        pageInfoShowDO = pageInfoShowService.getById(pageInfoShowDO.getId());
        if (ObjectValidators.isEmpty(pageInfoShowDO)) {
            throw getAppException("更新Featured数据失败：查询插入的数据失败");
        }
        return PageFeaturedVO.fromPageInfoShowDO(pageInfoShowDO, goodConvertVO);
    }

    /**
     * 根据id移除数据
     *
     * @param ids Featured据编号列表
     * @return 是否移除成功
     */
    @Override
    public boolean removeIndexFeaturedByIds(List<Integer> ids) {
        if (ObjectValidators.isEmpty(ids)) {
            throw getAppException("参数编号不能为空");
        }
        // 权限校验
        currentAdminUserCacheNotNull();
        return pageInfoShowService.remove(new LambdaUpdateWrapper<PageInfoShowDO>()
                .in(PageInfoShowDO::getId, ids)
                .eq(PageInfoShowDO::getPage, BusinessConstants.PAGE_NAME_INDEX)
                .eq(PageInfoShowDO::getModule, BusinessConstants.PAGE_MODULE_NAME_FEATURED));
    }
}
